const express = require('express');
const fs = require('fs');
const path = require('path');

const router = express.Router();  // 确保这是 express.Router()
const dataPath = path.join(__dirname, '../data/tasks.json');

// 读取任务数据
const readTasks = () => {
    try {
        const data = fs.readFileSync(dataPath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return [];
    }
};

// 保存任务数据
const saveTasks = (tasks) => {
    fs.writeFileSync(dataPath, JSON.stringify(tasks, null, 2));
};

// 获取所有任务
router.get('/', (req, res) => {
    const tasks = readTasks();
    res.json(tasks);
});

// 获取单个任务
router.get('/:id', (req, res) => {
    const tasks = readTasks();
    const task = tasks.find(t => t.id === parseInt(req.params.id));
    
    if (!task) {
        return res.status(404).json({ error: '任务未找到' });
    }
    
    res.json(task);
});

// 创建新任务
router.post('/', (req, res) => {
    const tasks = readTasks();
    const newTask = {
        id: Date.now(),
        title: req.body.title,
        completed: false,
        createdAt: new Date().toISOString()
    };
    
    tasks.push(newTask);
    saveTasks(tasks);
    res.status(201).json(newTask);
});

// 更新任务
router.put('/:id', (req, res) => {
    const tasks = readTasks();
    const taskIndex = tasks.findIndex(t => t.id === parseInt(req.params.id));
    
    if (taskIndex === -1) {
        return res.status(404).json({ error: '任务未找到' });
    }
    
    tasks[taskIndex] = { ...tasks[taskIndex], ...req.body };
    saveTasks(tasks);
    res.json(tasks[taskIndex]);
});

// 删除任务
router.delete('/:id', (req, res) => {
    const tasks = readTasks();
    const taskIndex = tasks.findIndex(t => t.id === parseInt(req.params.id));
    
    if (taskIndex === -1) {
        return res.status(404).json({ error: '任务未找到' });
    }
    
    tasks.splice(taskIndex, 1);
    saveTasks(tasks);
    res.status(204).send();
});

// 后端信息端点
router.get('/backend-info', (req, res) => {
    res.json({
        branch: 'feature/backend-api',
        features: [
            '任务创建API',
            '任务查询API', 
            '任务更新API',
            '任务删除API',
            '数据持久化'
        ],
        timestamp: new Date().toISOString()
    });
});

module.exports = router;  // 确保正确导出